package cnhy.salary.service;

import cnhy.salary.domain.Department;
import cnhy.salary.domain.Employee;
import cnhy.salary.domain.UserRef;
import cnhy.salary.domain.dto.EmployeeDto;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysUserService;
import ling.common.DataUtil;
import ling.common.EQueryService;
import ling.common.IDCardHelper;
import ling.common.domain.Result;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EmployeeSvc extends EQueryService<Employee> {
    public <T> void  employeeDtoFindSet(Collection<T> list, Function<T,Long> idFun, BiConsumer<T,EmployeeDto> predicate){
        var ids=list.stream().map(p->idFun.apply(p)).collect(Collectors.toList());
        var empDto=queryHelper.queryable(EmployeeDto.class).where(e -> e.in(EmployeeDto::getUserId,ids)).toList();
        DataUtil.findSet(list,empDto,(p,p1)-> Objects.equals(idFun.apply(p), p1.getUserId()),predicate);
    }
    @Transactional
    public Result addEmployees(boolean autoJobNum, Employee ...entities) {

        String msg = null;
        int i = 0;
        if(autoJobNum) {
            var nowMaxJobNum = jobNumCreate();
            for (var entity : entities)
                entity.setJobNum(++nowMaxJobNum + "");
        }
        for (var entity : entities) {
            i++;
            if (StringUtils.isBlank(entity.getJobNum()) || StringUtils.isBlank(entity.getName())) {
                msg += i + "-名称及工号不能为空\r\n";
            }

            //身份证推算
            if(!StringUtils.isBlank(entity.getCode())&&entity.getCode().length()>14) {
                if (entity.getBirthday() == null)
                    entity.setBirthday(IDCardHelper.birthday(entity.getCode()));
                if (entity.getSex() == null)
                    entity.setSex(IDCardHelper.getGender(entity.getCode()) ? 1 : 0);
            }


            var user = new UserRef();
            user.setUserName(entity.getJobNum());
            user.setNickName(entity.getName());
            user.setStatus("0");
            user.setCreateTime(new Date());
            user.setCreateBy(SecurityUtils.getUsername());
            user.setDeptId(entity.getDeptId());
            entity.setUser(user);
            if (entity.getEntryTime() == null)
                entity.setEntryTime(new Date());
            //queryHelper.query().insertable(entity).executeRows(true);
            //entity.setUserId(user.getUserId());
        }
        if (msg != null)
            return Result.bad(msg);

        var jobNumList = Arrays.stream(entities).map(p -> p.getJobNum()).collect(Collectors.toList());
        var repeatedData = queryHelper.entityQuery(Employee.class).where(e -> e.jobNum().in(jobNumList)).toList();
        if (repeatedData.size() > 0) {
            var strArr = repeatedData.stream().map(p -> p.getJobNum()).collect(Collectors.toList());
            var repeatedMsg = String.join(",", strArr);
            return Result.bad("工号重复:" + repeatedMsg);
        }
        var users = Arrays.stream(entities).map(p -> p.getUser()).collect(Collectors.toList());
        queryHelper.query().insertable(users).executeRows(true);
        for (var entity : entities) {
            entity.setUserId(entity.getUser().getUserId());
        }


        //设置默认角色
        var roleKey = "common";
        var role = new SysRole();
        role.setRoleKey(roleKey);
        var roleList = roleMapper.selectRoleList(role);
        var roleComm = roleList.get(0);
        var ruList = users.stream().map(p -> {
            var ru = new SysUserRole();
            ru.setUserId(p.getUserId());
            ru.setRoleId(roleComm.getRoleId());
            return ru;
        }).collect(Collectors.toList());
        userRoleMapper.batchUserRole(ruList);
        //获取外部id
        var m3Re = addM3Member(entities);
        queryHelper.query().insertable(Arrays.asList(entities)).executeRows();
//        var editList= Arrays.asList(entities).stream().filter(p->!StringUtils.isBlank(p.getSign())).collect(Collectors.toList());
//        queryHelper.query().updatable(editList).executeRows();
        var m3msg = "";
        if (m3Re.size() > 0) {
            m3msg = "添加成功,但打卡机人员注册失败：" + m3Re.size() + "条";
        }

        return Result.ok(m3msg);
    }
    public Long jobNumCreate(){
            //获取最大id,然后相加
        var maxId=queryHelper.queryable(Employee.class).maxOrDefault(Employee::getId,0L);
        return 100000+maxId;
    }
    public Result editEmployee(Employee entity){
        var re = super.edit(entity);
        var user = queryHelper.queryable(UserRef.class).whereById(entity.getUserId()).firstOrNull();
        if(!Objects.equals(user.getDeptId(), entity.getDeptId())&&user.getDeptId()!=null)
        {
            //部门变更，则移除部门领导职务
            var dept=queryHelper.entityQuery(Department.class)
                    .whereById(user.getDeptId())
                    .where(d -> d.leaderId().eq(user.getUserId()))
                    .firstOrNull();
            if(dept!=null)
            {
                dept.setLeaderId(null);
                dept.setLeader(null);
                queryHelper.entityQuery().updatable(dept).executeRows();
            }
        }
        user.setDeptId(entity.getDeptId());
        user.setNickName(entity.getName());
        user.setSex(entity.getSex()+"");
        queryHelper.queryClient().updatable(user).executeRows();
        return re;
    }

    public Result   reinstated(long userId) {

        var old = queryHelper.entityQuery(Employee.class).whereById(userId).firstOrNull();
        if (old.getResignTime() == null)
            return Result.bad("未离职");
        old.setResignTime(null);
        queryHelper.query().updatable(old).executeRows();
        log.info("复职："+old.getName()+"_"+old.getJobNum());
        return Result.ok();
    }
    @Resource
    M3HandlerSvc m3HandlerSvc;
    private List<Result<Employee>> addM3Member(Employee... entities) {
        var m3ReList = new ArrayList<Result<Employee>>();

        for (var emp : entities) {
            try {
                var re = m3HandlerSvc.createMember(emp);
                if (re.isSuccess() && !StringUtils.isBlank(re.getData() + ""))
                    emp.setSign(re.getData() + "");
                else
                {
                    m3ReList.add(Result.bad(re.getMsg(), emp));

                }
            } catch (Exception ex) {
                m3ReList.add(Result.bad("添加异常："+ex.getMessage(),emp));
            }
        }
        if(m3ReList.size()>0) {
            var logMsg = new StringBuilder();
            m3ReList.stream().map(p -> p.getMsg() + ":" + p.getData().getJobNum() + "," + p.getData().getName()).forEach(p -> logMsg.append(p).append(";"));
            log.error("---添加考勤机人员失败---"+logMsg.toString());
        }
        return m3ReList;

    }


    @Resource
    ISysUserService sysUserService;
    @Resource
    SysUserRoleMapper userRoleMapper;
    @Resource
    private SysRoleMapper roleMapper;
    @Transactional
    public  Result resign(Long id) {

        var old = queryHelper.entityQuery(Employee.class).whereById(id).firstOrNull();
        if (old.getResignTime() != null)
            return Result.bad("已离职");
        old.setResignTime(new Date());
        var user = new UserRef();
        user.setUserId(old.getUserId());
        user.setStatus("1");
        super.edit(old);
        queryHelper.query().updatable(user).setColumns(p->p.column(UserRef::getStatus)).executeRows();
        return Result.ok();
    }
}
